import json
import re

import execjs
import requests
import copy

from codes.commons.configs import easiest_common_headers as common_headers

# thanks to : https://github.com/cilame/any-whim

# 加载JS加密文件
with open('../../resources/match9/index_break.js', 'r', encoding='utf8') as f:
    js_code = f.read()

ctx = execjs.compile(js_code)


def get_info(page):
    def mk_url_headers():
        url = 'http://match.yuanrenxue.com/match/9'
        return url, common_headers

    f_url, f_headers = mk_url_headers()
    s = requests.get(f_url, headers=f_headers)
    m = ctx.call('get_m', re.findall(r"decrypt,'(\d+)'\)", s.text)[0])
    sessionid = re.findall('sessionid=[^;]+;', s.headers['Set-Cookie'])[0]

    def mk_url_headers(pp, sessionid_x, mm):
        url = 'http://match.yuanrenxue.com/api/match/9?page={}'.format(pp)
        headers = copy.deepcopy(common_headers)
        headers['Cookie'] = sessionid_x + "m={}".format(mm)
        return url, headers

    d_url, d_headers = mk_url_headers(page, sessionid, m)
    s = requests.get(d_url, headers=d_headers)
    return json.loads(s.text)


if __name__ == '__main__':
    all_values = []
    for page_num in range(1, 6):
        raw_data = get_info(page_num)
        print('page:{} --> raw_data:{}'.format(page_num, raw_data))
        values = [i['value'] for i in get_info(page_num)['data']]
        all_values.extend(values)

    _sum = sum(all_values)
    _len = len(all_values)
    print('平均值：{} (sum:{},len:{})'.format(_sum / _len, _sum, _len))
